using System.Linq;
using Sanelib.Common.SerializerHelper;

namespace Sanelib.CodeMaker.Generators
{
    public class Generator
    {
        public void AppendNewEntity(DatabaseTableSchema tableSchema)
        {
            DatabaseScriptGenerator.Generate(tableSchema);
            EntityGenerator.Generate(tableSchema);
            JavaScriptGenerator.Generate(tableSchema);
            CshtmlGenerator.Generate(tableSchema);
            ViewGenerator.Generate(tableSchema);
            ControllerGenerator.Generate(tableSchema);
            ControllerApiGenerator.Generate(tableSchema);
            CommandGenerator.Generate(tableSchema);

            var dbSchema = GetDatabaseSchema();         
            if (dbSchema.Tables.Any(t => tableSchema.TableName == t.TableName))
            {
                var table = dbSchema.Tables.First(t => t.TableName == tableSchema.TableName);
                dbSchema.Tables.Remove(table);
            }

            dbSchema.Tables.Add(tableSchema);

            Xml2Obj<DatabaseSchema>.Save(dbSchema);
        }

        public void RemoveEntity(string entityName)
        {
            var dbSchema = GetDatabaseSchema();

            if (dbSchema.Tables.Any(t => entityName == t.TableName))
            {
                var table = dbSchema.Tables.First(t => t.TableName == entityName);
                dbSchema.Tables.Remove(table);
            }

            Xml2Obj<DatabaseSchema>.Save(dbSchema);
        }

        private static DatabaseSchema GetDatabaseSchema()
        {
            var exist = Xml2Obj<DatabaseSchema>.IsExist();
            if (exist) return Xml2Obj<DatabaseSchema>.Load();
            var schema = new DatabaseSchema
            {
                DatabaseName = "TempDatabase",
                Description = "Temp description"
            };
            return schema;


        }
    }
}